package com.pj.lib.aura.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Calendar;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Log {
	private static FileHandler handler;
	private static FileHandler handlerDefault;
	private static String logCatalog;
	private static Logger logger;
	
	public static void setLogCatalog(String logCatalog) {
		Log.logCatalog = logCatalog;
	}
	
	public static void i(Object obj, String msg) {
		log(Level.INFO, obj, msg);
	}
	public static void w(Object obj, String msg) {
		log(Level.WARNING, obj, msg);
	}
	public static void s(Object obj, String msg) {
		log(Level.SEVERE, obj,msg);
	}
	public static void d(Object obj, String msg) {
		log(Level.FINEST, obj, msg);
		
	}
	
	public static void log(Level lvl, Object object, String msg) {
		if(logCatalog == null) {
			logCatalog = "";
		}
		try {
			handler = new FileHandler(logCatalog 
					+ object.getClass().getName() 
					+ "_" + Calendar.getInstance().get(Calendar.DAY_OF_MONTH) + "_" 
					+ (Calendar.getInstance().get(Calendar.MONTH) + 1) + "_" 
					+ Calendar.getInstance().get(Calendar.YEAR) + "_" + lvl.getName() + ".log", true);
			handlerDefault = new FileHandler(logCatalog 
					+ object.getClass().getName() 
					+ "_" + Calendar.getInstance().get(Calendar.DAY_OF_MONTH) + "_" 
					+ (Calendar.getInstance().get(Calendar.MONTH) + 1) + "_" 
					+ Calendar.getInstance().get(Calendar.YEAR) + ".log", true);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	    // Add to the desired logger
	    logger = Logger.getLogger("com.pj.lib.auraServer");
	    logger.addHandler(handler);
	    logger.addHandler(handlerDefault);
	    
	    logger.log(lvl, msg);
	    
	}
	
	public static String getStackTrace(Throwable aThrowable) {
	    final Writer result = new StringWriter();
	    final PrintWriter printWriter = new PrintWriter(result);
	    aThrowable.printStackTrace(printWriter);
	    return result.toString();
	  }
}
